import request from '@/utils/request.js'
import store from '@/store/index.js'

// 获取用户频道列表
export async function channels () {
  // 如果用户没登录
  if (!store.state.login.token) {
    // 获取本地存储的频道
    const _local = JSON.parse(localStorage.getItem('userChannels')) || []
    // 如果本地没数据
    if (_local.length === 0) {
      const res = await request({
        url: '/v1_0/user/channels'
      })
      localStorage.setItem('userChannels', res.data.channels)
      return res.data.channels
    } else {
      // 如果有数据 直接返回
      return _local
    }
  } else {
    const res = await request({
      url: '/v1_0/user/channels'
    })
    return res.data.channels
  }

  // return request({
  //   url: '/v1_0/user/channels'
  // })
}

// 获取新闻列表
export function articlesGet (params) {
  return request({
    url: '/v1_0/articles',
    params
  })
}

// 获取所有[频道列表]
export function channelsAll () {
  return request({
    url: '/v1_0/channels'
  })
}

// 全量修改 重置式
export async function userChannelsPut (channels) {
  // 如果有token
  if (store.state.login.token) {
    return request({
      url: '/v1_0/user/channels',
      method: 'put',
      data: {
        channels
      }
    })
  } else {
    localStorage.setItem('userChannels', JSON.stringify(channels))
  }
}
